<?php
function curlPost($url, $data = '', $headers = array(), $agent = '')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    //curl_setopt($ch, CURLOPT)
    $file_contents = curl_exec($ch);
    curl_close($ch);
    if ($file_contents === false) {
        throw new \Exception('CURL错误，错误代码：' . curl_errno($ch));
    }
    //这里解析
    return $file_contents;
}

/**
 * http get
 * @param $durl
 * @param array $headers
 * @return bool|string
 */
function curlGet($durl, $headers = array())
{
    // 初始化
    $curl = curl_init();
    // 设置url路径
    curl_setopt($curl, CURLOPT_URL, $durl);
    // 将 curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
    // 添加头信息
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    // CURLINFO_HEADER_OUT选项可以拿到请求头信息
    curl_setopt($curl, CURLINFO_HEADER_OUT, true);
    // 不验证SSL
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    // 执行
    $data = curl_exec($curl);
    // 打印请求头信息
//        echo curl_getinfo($curl, CURLINFO_HEADER_OUT);
    // 关闭连接
    curl_close($curl);
    // 返回数据
    return $data;
}

/**
 * 计划任务日志
 * @param $val
 */
function crontab_log($val)
{
    if (is_array($val)) {
        $val = var_export($val, true);
    }
    file_put_contents('crontab_log.txt', date('Y-m-d H:i:s', time()) . ' crontab : ' . $val . "\r\n", FILE_APPEND);
}

function tron_log($val)
{
    if (is_array($val)) {
        $val = var_export($val, true);
    }
    file_put_contents('tron_log.txt', date('Y-m-d H:i:s', time()) . 'IP:' . getRealIp() . ' tron : ' . $val . "\r\n", FILE_APPEND);
}

function err_log($val)
{
    if (is_array($val)) {
        $val = var_export($val, true);
    }
    file_put_contents('err_log.txt', date('Y-m-d H:i:s', time()) . ' error : ' . $val . "\r\n", FILE_APPEND);
}

function dev_log($val)
{
    if (is_array($val)) {
        $val = var_export($val, true);
    }
    file_put_contents('dev_log.txt', date('Y-m-d H:i:s', time()) . ' dev : ' . $val . "\r\n", FILE_APPEND);
}

function notify_log($val)
{
    if (is_array($val)) {
        $val = var_export($val, true);
    }
    file_put_contents('notify_log.txt', date('Y-m-d H:i:s', time()) . ' notify : ' . $val . "\r\n", FILE_APPEND);
}

function strMiddleReduceWordSensitive($string, $max = 42, $rep = '...')
{
    $strlen = strlen($string);
    if ($strlen <= $max) return $string;

    $lengthtokeep = $max - strlen($rep);
    $start = 0;
    $end = 0;

    if (($lengthtokeep % 2) == 0) {
        $start = $lengthtokeep / 2;
        $end = $start;
    } else {
        $start = intval($lengthtokeep / 2);
        $end = $start + 1;
    }

    $i = $start;
    $tmp_string = $string;
    while ($i < $strlen) {
        if (isset($tmp_string[$i]) and $tmp_string[$i] == ' ') {
            $tmp_string = substr($tmp_string, 0, $i) . $rep;
            $return = $tmp_string;
        }
        $i++;
    }

    $i = $end;
    $tmp_string = strrev($string);
    while ($i < $strlen) {
        if (isset($tmp_string[$i]) and $tmp_string[$i] == ' ') {
            $tmp_string = substr($tmp_string, 0, $i);
            $return .= strrev($tmp_string);
        }
        $i++;
    }
    return substr($string, 0, $start) . $rep . substr($string, -$end);
}

function admin_log($val)
{
    if (is_array($val)) {
        $val = var_export($val, true);
    }
    file_put_contents('admin_log.txt', date('Y-m-d H:i:s', time()) . ' admin : ' . $val . "\r\n", FILE_APPEND);
}

function getLastActivityTime($ip)
{
    return friendlyDate(S("ADMIN_IP_{$ip}"));
}

function getRealIp()
{
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            foreach ($arr as $ip) {
                $ip = trim($ip);

                if ($ip != 'unknown') {
                    $realip = $ip;
                    break;
                }
            }
        } else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } else if (isset($_SERVER['REMOTE_ADDR'])) {
            $realip = $_SERVER['REMOTE_ADDR'];
        } else {
            $realip = '0.0.0.0';
        }
    } else if (getenv('HTTP_X_FORWARDED_FOR')) {
        $realip = getenv('HTTP_X_FORWARDED_FOR');
    } else if (getenv('HTTP_CLIENT_IP')) {
        $realip = getenv('HTTP_CLIENT_IP');
    } else {
        $realip = getenv('REMOTE_ADDR');
    }

    preg_match('/[\\d\\.]{7,15}/', $realip, $onlineip);
    $realip = (!empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0');
    return $realip;
}

function getIpAddressName($ip)
{
    $address = S("IP_ADDRESS_{$ip}");
    if ($address == null) {
        $key = "6dcb43a85406b9e43166a9d9472eef4d";
        $url = "http://apis.juhe.cn/ip/ipNew?ip={$ip}&key=" . $key;
        $res = curlGet($url);
        $res = json_decode($res, true);
        if (intval($res['resultcode']) == 200) {
            $address = $res['result']['Country'] . $res['result']['Province'] . $res['result']['City'] . "(" . $res['result']['Isp'] . ")";
        } else {
            $address = null;
        }
    }
    S("IP_ADDRESS_{$ip}", $address);
    return $address;
}

function remoteCleanQueryUser($uid, $field)
{
    //$field = implode(",", $field;
    $url = C("SID_URL_CONFIG.apiUrl");
    $requestUrl = $url . "/app/cache/cleanCache";
    $post = [
        'uid' => $uid,
        'field' => $field
    ];
    curlPost($requestUrl, $post);
}
